package com.kinoshita.manager.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kinoshita.manager.service.impl.AdminUserDetailsService;
import com.kinoshita.manager.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, jsr250Enabled = true)
public class SecurityConfig {

    @Autowired
    private AdminUserDetailsService adminService;

    @Autowired
    private ObjectMapper objectMapper;

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new PasswordUtil();
    }

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        JsonAuthenticationFilter filter = new JsonAuthenticationFilter();
        filter.setAuthenticationManager(authenticationManager(http.getSharedObject(AuthenticationConfiguration.class)));
        filter.setAuthenticationSuccessHandler(new JsonLoginSuccessHandler(objectMapper));
        filter.setAuthenticationFailureHandler(new JsonLoginFailureHandler());
        filter.setFilterProcessesUrl("/manager/user/login");
        return http
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .exceptionHandling().authenticationEntryPoint(new JsonAuthenticationEntryPoint()).accessDeniedHandler(new JsonAccessDeniedHandler()).and()
                .authorizeRequests(authorize -> authorize
                        .antMatchers("/").permitAll()
                        .anyRequest().authenticated()
                )
                .userDetailsService(adminService)
                .addFilterAt(filter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }


}
